package com.zuozhj.controller;


import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

// import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zuozhj.common.Result;
import com.zuozhj.common.dto.SysMenuDTO;
import com.zuozhj.entity.SysMenu;

import com.zuozhj.entity.SysUser;
// import com.zuozhj.entity.SysRoleMenu;
// import com.zuozhj.service.ISysRoleMenuService;

import cn.hutool.core.map.MapUtil;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zuozhj
 * @since 2022-12-02
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController {

    // @Autowired
    // ISysRoleMenuService sysRoleMenuService;
    
    @RequestMapping("/nav")
    public Result nav(Principal principal) {
        SysUser sysUser = sysUserService.getByUsername(principal.getName());
               
        String authorityInfo = sysUserService.getUserAuthorityInfo(sysUser.getId());
        
        // 分割字符串
        String[] authorityInfoArray = StringUtils.tokenizeToStringArray(authorityInfo, ",");

        List<SysMenuDTO> navs = sysMenuService.getCurrentUserNav();

        return Result.success(
                MapUtil.builder()
                    .put("authorities", authorityInfoArray)
                    .put("nav", navs)
                    .build()
            );
    }

    @PreAuthorize("hasAuthority('sys:menu:list')")
    @RequestMapping("/info/{id}")
    public Result info(@PathVariable(name = "id") Long id) {

        SysMenu sysMenu = sysMenuService.getById(id);

        return Result.success(sysMenu);
    }


    @PreAuthorize("hasAuthority('sys:menu:list')")
    @RequestMapping("/list")
    public Result list() {

        List<SysMenu> menus = sysMenuService.tree();

        return Result.success(menus);
    }

    @PreAuthorize("hasAuthority('sys:menu:save')")
    @RequestMapping("/save")
    public Result save(@Validated @RequestBody SysMenu sysMenu) {

        sysMenu.setCreatedAt(LocalDateTime.now());

        sysMenuService.save(sysMenu);

        return Result.success(sysMenu);
    }

    @PreAuthorize("hasAuthority('sys:menu:update')")
    @RequestMapping("/update")
    public Result udpate(@Validated @RequestBody SysMenu sysMenu) {

        sysMenu.setUpdatedAt(LocalDateTime.now());

        sysMenuService.updateById(sysMenu);

        // 修改菜单需要同时删除菜单权限的缓存 
        sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());

        return Result.success(sysMenu);
    }

    @PreAuthorize("hasAuthority('sys:menu:delete')")
    @RequestMapping("/delete/{id}")
    public Result delete(@PathVariable(name = "id") Long id) {

        int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if (count > 0) {
            return Result.fail("请先删除子菜单");
        }

        // 删除菜单需要同时删除菜单权限的缓存 
        sysUserService.clearUserAuthorityInfoByMenuId(id);

        sysMenuService.removeById(id);

        // 删除中间表相关数据 SysRoleMenu, 数据库做了外键关联可以不写下面代码
        // sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id", id));

        return Result.success("");
    }
}
